import React, { useState, useCallback } from 'react';
import { Common } from 'UtilsCommon';
import { useGetDataSourceOptions } from 'UseHooks';
import { Menu } from 'antd';
import { Icon } from 'Configs';
import Base from './base';

const renderLabelItem = (m, i) => {
    return <div className='divLabelItem' key={i}><span>{m}</span></div>;
};

const getOptions = (property, view, pageAxis, parentValue) => {
    const { dataSource, valueName, textName } = property;

    const options = [];

    let value = null; let text = null;
    Common.isArray(dataSource) && dataSource.forEach(d => {
        text = d[textName];
        value = d[valueName];
        if (Common.isArray(text)) text = text.map((m, i) => renderLabelItem(m, i));
        const option = { label: text, key: value };
        if (property.iconType) option.icon = <Icon type={property.iconType} />;
        options.push(option);
    });

    return options;
};

export default (props) => {
    const { property, view, pageAxis } = Base.getProps(props);
    const [selectedKeys, setselectedKeys] = useState(property.selectedKeys || []);
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);

    const [options, setOptions] = useGetDataSourceOptions(property, view, pageAxis, getOptions);

    const onSelect = useCallback(({ item, key }) => {
        setselectedKeys([key]);
        property.onSelectItem && property.onSelectItem(item, key);
    }, [property, setselectedKeys]);

    property.setIsVisible = (v) => setIsVisible(v);
    property.setselectedKeys = (v) => setselectedKeys(v);
    property.refreshOptions = () => setOptions(getOptions(property, view, pageAxis));

    if (!isVisible || options.length === 0) return null;

    const { cssTemplate, className, style } = property;

    const cNames = [];
    if (className) cNames.push(className);
    if (cssTemplate) cNames.push(cssTemplate.cssName);

    const selectedKeys2 = selectedKeys.length > 0 ? selectedKeys : (options.length > 0 ? [options[0].key] : []);

    return <Menu theme="light" style={Base.setStyle(style)} className={cNames.join(' ')} items={options} mode="inline" selectedKeys={selectedKeys2} onSelect={onSelect} />;
};